using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using facebook.Components;
using facebook.desktop.Properties;
using facebook.Schema;
using System.Net;

namespace facebook.desktop
{
	[ToolboxItem(true), ToolboxBitmap(typeof (BaseControl))]
	public partial class PhotoAlbum : BaseControl
	{
		public delegate album GetAlbumPhotosHandler();
		public delegate void LoadImageHandler(int index);
        internal static album NewAlbum; 
		private IList<album> _albums;
		private int _currentImageIndex;
		private IList<photo> _photos;
		private string _selectedPath = string.Empty;
        private bool large_image;

        int downprog;

        public bool Large_image
        {
            get { return large_image; }
            set { large_image = value; }

        }
        public int ImageDownloadProgress
        {

            get { return downprog; }
        }

		public PhotoAlbum()
		{
			InitializeComponent();
		}
        public IList<photo> photos
        {
            get { return _photos ; }

        }
        public int currentImageIndex
        {
            get { return _currentImageIndex; }

        }
		[Category("Facebook")]
		[Description("")]
		public IList<album> Albums
		{
			get { return _albums; }
			set
			{
				_albums = value;
				OnLoad();
			}
		}

		[Category("Facebook"), Description("")]
		public FacebookService FacebookService { get; set; }

		private void OnLoad()
		{
			if (!IsDesignTime() && FacebookService != null && _albums != null)
			{
				LoadAlbums();
			}
		}

		private void LoadAlbums()
		{
			cboAlbums.Items.Clear();

			if (_albums.Count > 0)
			{
				foreach (var album in _albums)
				{
					cboAlbums.Items.Add(album);
				}
				cboAlbums.DisplayMember = "name";
				cboAlbums.ValueMember = "aid";

				cboAlbums.SelectedIndex = 0;
			}
			else
			{
				pbPhoto.Image = Resources.missingPicture;
				lblPhotoCount.Text = string.Empty;
				lblTag.Text = string.Empty;
				_photos = null;
				cboAlbums.Text = string.Empty;
			}
		}

		private void lbnext_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			OnChangeImage(1);
		}

		private void lbPrevious_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			OnChangeImage(-1);
		}

		private void cboAlbums_SelectedIndexChanged(object sender, EventArgs e)
		{
			_photos = null;
			lblPhotoCount.Text = GetSelectedAlbum().name + " album is loading.";
			lblTag.Text = "  Please wait...";
			pbPhoto.Image = Resources.missingPicture;
			var backgroundThread = new Thread(LoadPhotos);
			backgroundThread.Start();
		}

		private void LoadPhotos()
		{
			if (FacebookService == null) return;
			_photos = FacebookService.photos.get(null,GetSelectedAlbum().aid,null);
			LoadImage(0);
		}

		public album GetSelectedAlbum()
		{
			return InvokeRequired
			       	? (album) Invoke(new GetAlbumPhotosHandler(GetSelectedAlbum), null)
			       	: (album) cboAlbums.SelectedItem;
		}

		private void LoadImage(int index)
		{
			if (InvokeRequired)
			{
				var parms = new object[1];
				parms[0] = index;
				Invoke(new LoadImageHandler(LoadImage), parms);
			}
			else
			{
				if (_photos != null && _photos.Count > 0)
				{
					if (_photos[index].src_big != null)
					{
                        if (this.Large_image == true)
                        {
                            pbPhoto.ImageLocation = _photos[index].src_big;

                        }
                        else
                        {

                            pbPhoto.ImageLocation = _photos[index].src;
                            
                        }
					}
					else
					{
                        if (this.Large_image == true)
                        {
                            pbPhoto.Image = _photos[index].picture_big;
                        }
                        else
                        {
                            pbPhoto.Image = _photos[index].picture ;
                        }
					}
					lblPhotoCount.Text = String.Format(CultureInfo.InvariantCulture, "{0} of {1}", index + 1, _photos.Count);
					lblTag.Text = _photos[index].caption;
                    
					_currentImageIndex = index;
				}
			}
		}

		private void OnChangeImage(int direction)
		{
			if (_photos == null) return;

			var nextIndex = _currentImageIndex + direction;

			if (nextIndex >= _photos.Count)
			{
				_currentImageIndex = 0;
			}
			else if (nextIndex < 0)
			{
				_currentImageIndex = _photos.Count - 1;
			}
			else
				_currentImageIndex = nextIndex;

			LoadImage(_currentImageIndex);
		}

		private void OnExport()
		{
			if (_photos == null) return;

			if (fbdExport.ShowDialog() == DialogResult.OK)
			{
				_selectedPath = fbdExport.SelectedPath;
				var backgroundThread = new Thread(SaveImages);
				backgroundThread.Start();
			}
		}

		private void SaveImages()
		{
			foreach (var photo in _photos)
			{
				Thread.Sleep(200);

				var bitmap = new Bitmap(photo.picture);
				bitmap.Save(Path.Combine(_selectedPath, photo.pid + ".jpg"), ImageFormat.Jpeg);
			}
		}

		private void btnExport_Click(object sender, EventArgs e)
		{
			OnExport();
		}
        private void btnSavePhoto_Click(object sender, EventArgs e)
        {
            try
            {
                album actalbum = this.GetSelectedAlbum();
                WebClient wbclient = new WebClient();
                DialogResult dialogres = saveFileDialog.ShowDialog();
                if ((actalbum != null) && (dialogres  == DialogResult.OK))
                    
                {
                    if (saveFileDialog.FileName == null)
                    {
                        photo phot = photos[this.currentImageIndex];
                        //saveFileDialog.FileName = Path.GetFileName(phot.src_big);
                        string filename = Path.Combine(Path.GetDirectoryName(saveFileDialog.FileName), Path.GetFileName(phot.src_big));
                        //this.lblTag.Text = Path.GetFileName(phot.src_big);

                        wbclient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.imageDownloadCompeted);
                        wbclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DowloadProgchanged);
                        wbclient.DownloadFile(phot.src_big, filename);
                    }
                    else
                    {
                        photo phot = photos[this.currentImageIndex];
                        //saveFileDialog.FileName = Path.GetFileName(phot.src_big);
                       // string filename = Path.Combine(Path.GetDirectoryName(saveFileDialog.FileName), Path.GetFileName(phot.src_big));
                        //this.lblTag.Text = Path.GetFileName(phot.src_big);

                        wbclient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.imageDownloadCompeted);
                        wbclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DowloadProgchanged);
                        wbclient.DownloadFile(phot.src_big, saveFileDialog.FileName);

                    }

                }



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }
        void imageDownloadCompeted(object send, AsyncCompletedEventArgs e)
        {

            try
            {
               
                //this.ProgressBar.Visible = false;


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }
      
        private void DowloadProgchanged(object send, DownloadProgressChangedEventArgs e)
        {
            try
            {
                downprog = e.ProgressPercentage;
              //  this.ProgressBar.Value = this.ImageDownloadProgress;



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }

        }

        private void btnSaveAlbum_Click(object sender, EventArgs e)
        {
            try
            {
                album actalbum = this.GetSelectedAlbum();
                if ((actalbum != null) && (folderDialog.ShowDialog() == DialogResult.OK)
                    && (folderDialog.SelectedPath != null))
                {

                    foreach (photo phot in this.FacebookService.photos.get(null, actalbum.aid, null))
                    {
                        string filename = Path.Combine(folderDialog.SelectedPath, Path.GetFileName(phot.src_big));

                       //Bitmap pic = new Bitmap(phot.picture_big);
                        //pic.Save(filename, ImageFormat.Jpeg);
                        WebClient wbclient = new WebClient();
                      //  this.ProgressBar.Visible = true;
                        wbclient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.imageDownloadCompeted);
                        wbclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DowloadProgchanged);
                        wbclient.DownloadFile(phot.src_big, filename);
                        

                    }

                }



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void PhotoAlbum_Load(object sender, EventArgs e)
        {
            try
            {
                

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
            
        }

        private void btnCreateAlbum_Click(object sender, EventArgs e)
        {
            try
            {

                if (FacebookService != null)
                {
                    CreateAlbum createalb = new CreateAlbum(FacebookService);
                    createalb.Show();
                    
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
             try
             {
                 if ((FacebookService != null) &&(openFile.ShowDialog() == DialogResult.OK )
                 &&(openFile.FileName !=null ) &&(this.GetSelectedAlbum()!=null))
                {
                    FacebookService.photos.upload(this.GetSelectedAlbum().aid, null, new FileInfo(openFile.FileName));

                    
                }
                 


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }

        }

        private void btnRemove_Click(object sender, EventArgs e)
        {


            try
            {
                if ((FacebookService != null) && (openFile.ShowDialog() == DialogResult.OK)
                && (openFile.FileName != null) && (this.GetSelectedAlbum() != null))
                {
                    FacebookService.photos.upload(this.GetSelectedAlbum().aid, null, new FileInfo(openFile.FileName));


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
                 
        }
        protected override void OnGotFocus(EventArgs e)
        {
            try
            {
                pbPhoto.Select();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void PhotoAlbum_Resize(object sender, EventArgs e)
        {



            try
            {

                if (this.ParentForm!=null )
                {
                if (this.ParentForm.WindowState == FormWindowState.Maximized)
                {
                    this.Large_image = true;
                    this.LoadImage(_currentImageIndex);

                }
                else
                {
                    this.Large_image = false;
                    this.LoadImage(_currentImageIndex);

                }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void PhotoAlbum_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if(e.KeyCode== Keys.Right )
                {
                    OnChangeImage(1); ;

                }
                else if(e.KeyCode==Keys.Left)
                {
                    OnChangeImage(-1);

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }

        }

        private void pbPhoto_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Right)
                {
                    OnChangeImage(1); ;

                }
                else if (e.KeyCode == Keys.Left)
                {
                    OnChangeImage(-1);

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }

        }

        private void cboAlbums_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Right)
                {
                    OnChangeImage(1); ;

                }
                else if (e.KeyCode == Keys.Left)
                {
                    OnChangeImage(-1);

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void btnRotateLeft90_Click(object sender, EventArgs e)
        {
            try
            {
                pbPhoto.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                pbPhoto.Refresh();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void btnRotateRight90_Click(object sender, EventArgs e)
        {
            try
            {
                pbPhoto.Image.RotateFlip(RotateFlipType.Rotate90FlipX);
                pbPhoto.Refresh();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void saveAllAlbumsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
               
                if ( (folderDialog.ShowDialog() == DialogResult.OK)
                    && (folderDialog.SelectedPath != null))
                {
                    if (Albums.Count > 0)
                    {

                        foreach (album alb in Albums)
                        {
                            foreach (photo phot in this.FacebookService.photos.get(null, alb.aid, null))
                            {
                                if (Directory.Exists(Path.Combine(folderDialog.SelectedPath, alb.name)) == false)
                                {

                                    Directory.CreateDirectory(Path.Combine(folderDialog.SelectedPath, alb.name));


                                }
                                string filename = Path.Combine(Path.Combine(folderDialog.SelectedPath, alb.name), Path.GetFileName(phot.src_big));
                                //Bitmap pic = new Bitmap(phot.picture_big);
                                //pic.Save(filename, ImageFormat.Jpeg);
                                WebClient wbclient = new WebClient();
                                //  this.ProgressBar.Visible = true;
                                wbclient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.imageDownloadCompeted);
                                wbclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DowloadProgchanged);
                                wbclient.DownloadFile(phot.src_big, filename);


                            }
                        }
                    }

                }



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        

	}
}